package com.huan.atm;


import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class BankServer {
    private static Logger logger = Logger.getLogger(BankServer.class);
    public static void main(String[] args) throws IOException {
        //线程池核心线程数
        int corePoolSize = 3;
        //线程池最大线程数
        int maxiPoolSize = 5;
        //最大空闲时间，超过则销毁线程
        long keepAliveTime = 10;
        //枚举 时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        //有界阻塞列 容量为2
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2);
        //线程创建工厂
        ThreadFactory threadFactory = new NameThreadFactory();
        //线程池拒绝策略
        RejectedExecutionHandler handler = new MyIgnorePolicy();
        //线程池 通常使用执行器
        ThreadPoolExecutor executor = null;
        //推荐的创建线程池方法（不推荐使用现成的API创建线程池）：
        executor = new ThreadPoolExecutor(corePoolSize,maxiPoolSize,keepAliveTime,unit,workQueue,threadFactory,handler);
        //预启动核心线程 提升效率
        executor.prestartAllCoreThreads();
        //执行任务
        //任务数
        Bank bank = new Bank();
        ServerSocket socket = new ServerSocket(10020);
        logger.info("银行服务器启动，监听"+socket.getLocalPort());
        boolean flag = true;
        while (flag){
            Socket s = socket.accept();
            System.out.println("ATM客户端"+s.getRemoteSocketAddress()+"连接成功");
            //商业项目必须使用线程池
            BankTask task = new BankTask(s,bank);
            //提交任务到线程池
            executor.submit(task);
        }
        executor.shutdown();
    }
    static class NameThreadFactory implements ThreadFactory{
        //线程id AtomicInteger 原子整型类
        private final AtomicInteger threadId = new AtomicInteger(1);
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r,"线程-"+threadId.getAndIncrement());
            System.out.println(t.getName()+"已经创建");
            return t;
        }
    }

    //线程池拒绝策略
    public static class MyIgnorePolicy implements RejectedExecutionHandler{

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            doLog(r,executor);
        }
        private void doLog(Runnable r, ThreadPoolExecutor executor){
            //做日志记录
            System.err.println("线程池:"+executor.toString()+r.toString()+"被拒绝");
        }
    }
}
